package com.changgou.controller;

import com.changgou.service.EsManagerService;
import com.changgou.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private EsManagerService esManagerService;

    @Autowired
    private SearchService searchService;

    //对搜索入参带有特殊符号进行处理
    public void handlerSearchMap(Map<String,String> searchMap){
        //如果参数为空则不处理
        if (searchMap!=null){
            //获取查询条件map的每一个键值对
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            //遍历键值对 如果有spec_开头的(规格) 获取它的值 把值中的 "+" 替换成 %2B
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")){
                    //浏览器入参无法识别 + 参数中+替换成%2B
                    searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                    System.out.println(searchMap.get(entry.getKey()));
                }
            }
        }
    }
    /**
     * paramMap (参数map集合)
     * 全文检索
     */
    @GetMapping("/list")
    public String search(@RequestParam Map<String,String> paramMap, Model model) throws Exception {
        //先处理参数在调用方法查询
        handlerSearchMap(paramMap);
        //调用service方法 获取查询结果的map集合.
        Map resultMap = searchService.search(paramMap);

        //将查询结果封装到MODEL中返回到前端页面 进行thymeleaf页面静态化
        model.addAttribute("searchMap",paramMap);
        model.addAttribute("result",resultMap);

        //拼装Url
        StringBuilder url=new StringBuilder("/search/list");
        if (paramMap!=null&&paramMap.size()>0){
            url.append("?");
            for (String key : paramMap.keySet()) {
                if (!"sortRule".equals(key)&&!"sortField".equals(key)&&!"pageNum".equals(key)){
                    url.append(key).append("=").append(paramMap.get(key)).append("&");
                }
            }
            String urlString = url.toString();
            //去除路径上最后一个&
            urlString = urlString.substring(0, url.length() - 1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }
        //由于页面是thymeleaf 完成的 属于服务器内页面渲染 跳转页面
        return "search";
    }

}
